/* eslint-disable no-param-reassign */
import { Plugin } from 'rollup';
import { createFilter } from '@rollup/pluginutils';
import glob from 'fast-glob';
import path from 'path';

export interface PluginOptions {
  /**
   * 项目根目录
   *
   * @author chitanda
   * @date 2023-05-19 18:05:56
   * @type {string}
   */
  rootDir: string;
  /**
   * 忽略的文件
   *
   * @author chitanda
   * @date 2023-05-19 18:05:24
   * @type {string[]}
   */
  exclude?: string[];
}

const plugin = (opts: PluginOptions): Plugin => {
  const rootDir = path.resolve(opts.rootDir);
  const filter = createFilter([path.resolve(rootDir, '**/*.ts')]);

  const input = glob.sync('**/*.ts', {
    cwd: rootDir,
    absolute: true,
    onlyFiles: true,
    ignore: opts.exclude || [],
  });

  return {
    name: 'external-all-node-modules',
    buildStart(opt) {
      opt.input = input;
    },
    resolveId(id) {
      if (!filter(id)) {
        return {
          id,
          external: true,
        };
      }
      return null;
    },
  };
};

export default plugin;
